﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;

#if ExcelByNpoi

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Library.Excel
{
    /// <summary>
    /// 引用 ICSharpCode.SharpZipLib.dll
    /// 引用 System.Data.dll
    /// 引用 NPOI
    /// 引用 NPOI.OOXML
    /// 引用 NPOI.OpenXml4Net
    /// 引用 NPOI.OpenXmlFormats
    /// </summary>
    internal class ExcelByNpoi : ExcelByBase
    {
        /// <summary>
        /// 获取单元格类型
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        protected static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
         
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC: 
                    {
                        if (DateUtil.IsCellDateFormatted(cell))
                            return cell.DateCellValue; //修正日期显示
                        return cell.NumericCellValue; //返回正常数字
                    }
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                    IWorkbook workbook = cell.Row.Sheet.Workbook;
                    switch (workbook)
                    {
                        case XSSFWorkbook _:
                            return GetValueType(new XSSFFormulaEvaluator(workbook).EvaluateInCell(cell));
                        case HSSFWorkbook _:
                            return GetValueType(new HSSFFormulaEvaluator(workbook).EvaluateInCell(cell));
                        default:
                            return cell.CellFormula;
                    }
                default:
                    return "";
            }
        }

        /// <summary>
        /// Excel导入成Datable
        /// </summary>
        /// <param name="file">导入路径(包含文件名与扩展名)</param>
        /// <returns></returns>
        public static IEnumerable<DataTable> ImportExcelToDataTable(string file, int keyLine = -1, int SkipRows = 0, int SkipColumns = 0, int TakeColumns = int.MaxValue)
        {
            foreach (IWorkbook workbook in YieldReturnWorkbookForReader(file))
            {
                foreach (ISheet sheet in workbook)
                {
                    DataTable dt = new DataTable();

                    dt.TableName = sheet.SheetName;

                    List<object[]> result = new List<object[]>();

                    foreach (IRow row in sheet)
                    {
                        result.Add(row.Cells.Select(p => GetValueType(p)).Skip(SkipColumns).Take(TakeColumns).ToArray());
                    }

                    if (keyLine == -1)
                    {
                        for (int i = 0; i < result.Max(p => p.Length); i++)
                        {
                            dt.Columns.Add();
                        }
                    }
                    else
                    {
                        foreach (var line in result.Skip(keyLine))
                        {
                            foreach (var item in line)
                            {
                                dt.Columns.Add(item.ToString());
                            }
                            break;
                        }
                    }

                    foreach (var item in result.Skip(SkipRows))
                    {
                        dt.Rows.Add(item);
                    }

                    yield return dt;
                }
            }
        }

        /// <summary>
        /// Datable导出成Excel
        /// </summary>
        /// <param name="file">导出路径(包括文件名与扩展名)</param>
        /// <param name="dts"></param>
        public static void ExportDataTableToExcel(string file, params DataTable[] dts)
        {
            string fileExt = Path.GetExtension(file).ToLower();
            foreach (IWorkbook workbook in YieldReturnWorkbookForWrite(file))
            {
                foreach (DataTable dt in dts)
                {
                    if (fileExt == ".xls" && dt.Rows.Count > 65536)
                    {
                        throw new Exception("数据量过大，请保存为.xlsx");
                    }

                    ISheet sheet = workbook.CreateSheet(string.IsNullOrEmpty(dt.TableName) ? "Sheet1" : dt.TableName);

                    //表头  
                    Dictionary<string, HashSet<int>> charactersDict = new Dictionary<string, HashSet<int>>();

                    IRow row = sheet.CreateRow(0);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        ICell cell = row.CreateCell(i);
                        var value = dt.Columns[i].ColumnName;
                        cell.SetCellValue(value);
                        charactersDict[value] = new HashSet<int>() { value.Length };
                    }

                    //数据  
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        IRow row1 = sheet.CreateRow(i + 1);
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            var value = dt.Rows[i][j];
                            ICell cell = row1.CreateCell(j);

                            switch (value)
                            {
                                case int @int:
                                    cell.SetCellValue(@int);
                                    break;
                                case bool boolean:
                                    cell.SetCellValue(boolean);
                                    break;
                                default:
                                    cell.SetCellValue(value.ToString());
                                    break;
                            }

                            charactersDict[dt.Columns[j].ColumnName].Add(value.ToString().Length);
                        }
                    }

                    //默认一个样式以及
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        var style = workbook.CreateCellStyle();
                        sheet.SetDefaultColumnStyle(i, style);

                        //sheet.AutoSizeColumn(i); //自动宽度

                        var columnWidth = charactersDict[dt.Columns[i].ColumnName].OrderBy(p => p).Skip(1).Reverse().Skip(1).FirstOrDefault();
                        sheet.SetColumnWidth(i, Math.Min(columnWidth, 50) * 256);
                    }
                }
            }
        }

        public static IEnumerable YieldReturnWorkbookForWrite(string file)
        {
            new FileInfo(file).Directory.Create();
            using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
            {
                IWorkbook workbook = null;
                string fileExt = Path.GetExtension(file).ToLower();
                switch (fileExt)
                {
                    case ".xlsx":
                    case ".xlsm":
                        workbook = new XSSFWorkbook();
                        break;
                    case ".xls":
                        workbook = new HSSFWorkbook();
                        break;
                    default:
                        throw new Exception("保存的文件格式不符合要求 ！");
                }

                yield return workbook;
                workbook.Write(fs);
            }
        }

        public static IEnumerable<IWorkbook> YieldReturnWorkbookForReader(string file)
        {
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                switch (fileExt)
                {
                    case ".xlsx":
                    case ".xlsm":
                        yield return new XSSFWorkbook(fs);
                        break;
                    case ".xls":
                        yield return new HSSFWorkbook(fs);
                        break;
                    default:
                        throw new Exception("文件格式不符合要求 ！");
                }
            }
        }
    }
}

#endif